const { API_ROOT, PORT } = require('./settings');
const mockDataRootPath = './settings/data/';

const Koa = require('koa');
const http = require('http');
const fs = require('fs');

const router = require('koa-router')();
const app = new Koa();

const utils = require('./lib/utils');

app.use(async (ctx, next) => {
  try {
    await next();
    const status = ctx.status || 404
    if (status === 404) {
        ctx.throw(404)
    }
  } catch (err) {
    ctx.response.body = {
      status: 0,
      error: {
        code: err.status,
        msg: err.message
      }
    };
  }
});

router.post(`${API_ROOT}/**`, async (ctx, next) => {
  let settings = utils.getRespSettings(ctx.request.url);
  console.log(`${mockDataRootPath}${settings.path}.json`);
  let respData = fs.readFileSync(`${mockDataRootPath}${settings.path}.json`);

  return new Promise(resolve => {
    setTimeout(resolve, 500);
  })
  .then(() => {
      return next().then(() => {
        ctx.status = settings.status;
        ctx.response.body = JSON.parse(respData);
      });
  });
  
});

router.get(`${API_ROOT}/**`, async (ctx, next) => {
  let settings = utils.getRespSettings(ctx.request.url);
  console.log(`${mockDataRootPath}${settings.path}.json`);
  let respData = fs.readFileSync(`${mockDataRootPath}${settings.path}.json`);

  return new Promise(resolve => {
    setTimeout(resolve, 500);
  })
  .then(() => {
      return next().then(() => {
        ctx.status = settings.status;
        ctx.response.body = JSON.parse(respData);
      });
  });
  
});

app.use(router.routes());

http.createServer(app.callback()).listen(PORT, () => {
  console.log(`Server is running on: http://localhost:${PORT}`);
});